var request_url = 'form.xml';
var development = false;

function debug(text) {
	if(development)
		alert(text);
}

function generateForm(url, data) {
	if(url == null) return;
	var formPanel = null;
	$.ajax({
		type: 'get',
		url: url,
		async: false,
		dataType: 'xml',
		complete: function(xml) { formPanel = buildForm(xml, data);}
	});
	return formPanel;
}

buildForm = function(xml, data) {
	debug('XML: ' + $($("formspec", xml.responseXML).get(0)).text());
	var _form_url = $($("action", xml.responseXML).get(0)).text();
	// Verificamos que la respuesta del servidor sea la esperada. En caso contrario se retorna null
	if(xml.status == 200 && xml.getResponseHeader('Content-Type').indexOf('xml') > 0) {
		debug('Generando form panel con ' + xml.responseXML);
		var formIds = Array();
		var formID = $($("/formspec/name", xml.responseXML).get(0)).text();
		var formAction = $($("/formspec/action", xml.responseXML).get(0)).text();
		debug('FORMACTION: ' + formAction);
		var formPanel = new Ext.form.FormPanel({  
				id: formID,
				frame: true,
				title:'Agregar',
				collapsible: true,
				labelAlign: 'right',
				labelWidth: 85,
				waitMsgTarget: true,
				waitMsg:'Guardando...',
				url: _form_url
			});
			
		var component = null;
		debug($("/formspec/fields/field", xml.responseXML).text());
		$("/formspec/fields/field", xml.responseXML).each(function(i){
			_id = formID + this.attributes.getNamedItem('name').value;
			_label = $($("label", this).get(0)).text();
			_type = $($("type", this).get(0)).text();
			_default = $($("default", this).get(0)).text();
			formIds[i] = _id;
			component = fieldFactory(_id, _type, _label, this);
			if(_default != null) {
				component.setValue(_default);
			}
			if(component != null) {
				formPanel.add(component);
			}
		});
		
		formPanel.successHandler = successHandler;
		formPanel.addButton({
			id: formID,
			text: 'Agregar',
			handler: function() {	
					if (formPanel.form.isValid()) {
						xmlDocument = '<?xml version="1.0" encoding="UTF-8" ?>';
						xmlDocument += '<' + formPanel.id + '>';
						
						for(i = 0; i < formIds.length; i++) {
							item_component = formPanel.form.items.get(formIds[i]);
							debug(formPanel.form.items.get(formIds[i]))
							xmlDocument += '<' + item_component.id.substring(formID.length) + '>' + item_component.getValue() + '</'+ item_component.id.substring(formID.length) +'>';
						}
						xmlDocument += '</' + formPanel.id + '>';
						debug(xmlDocument);
						debug(xmlDocument);
						$.ajax({
						  type: "post",
						  url: formAction,
						  dataType: "xml",
						  async: false,
						  data:{xml: xmlDocument},
						  complete: function(xml) {formPanel.successHandler(xml, data);}
						});
						
					} else {
							Ext.MessageBox.alert('Errores', 'Por favor, corrija los errores.');
					}		
				}
		});
		return formPanel;
	} else {
		debug('STATUS: ' + xml.status + ' CONTENT-TYPE: ' + xml.getResponseHeader('Content-Type'));
	}			
};

var successHandler = function(xml, data) {
		if(xml.status != 201) {
			debug(xml.status);
			Ext.MessageBox.alert('Error', 'El elemento no pudo ser agregado');
		} else {
			//Ext.MessageBox.alert('Exito', 'El elemento fue agregado');
			if(data != null) {
				data.reload();
			}
		}
};
	
var fieldFactory = function(id, type, label, fieldXML) {
	var result = null;
	var validations = $('validations', fieldXML);
	if (type == 'select') {
		if(fieldXML != null) {
			var data_url = $($('options', fieldXML)[0]).attr('href');
			var data_record = $($('options', fieldXML)[0]).attr('name'); //Nombre del tag en el doc XML que contiene las opciones del combobox
			var children = $("/options/option", fieldXML).children()
			var data_id = $("options/option", fieldXML).children()[0].tagName; //Id del campo para ser mostrado en el combobox
			var data_name = $("options/option", fieldXML).children()[1].tagName; // Nombre para ser mostrado en el combobox
			
			result = new Ext.form.ComboBox({
							id: id,
							fieldLabel: label,
							store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({method: 'get', url: data_url}),
														 reader: new Ext.data.XmlReader({
																		record: data_record,
																		id: data_id
																	}, [data_id, data_name]) 
								}), 
							displayField: data_name,
							valueField: data_id,
							typeAhead: true,
							mode: 'remote',
							triggerAction: 'all',
							editable: false,
							selectOnFocus: true,
							loadingText: 'Cargando...',
							width: 170
					});
			setValidations(result, validations);
		}
	} else if(type == 'text') {
		result = new Ext.form.TextField({id: id, fieldLabel: label, width: 170});
		setValidations(result, validations);
	} else if(type == 'textarea') {
		result = new Ext.form.TextArea({id: id, fieldLabel: label, width: 170});
		setValidations(result, validations);
	} else if(type == 'date') {
		result = new Ext.form.DateField({id: id, fieldLabel: label});
		setValidations(result, validations);
	}
	return result;
};

function setValidations(component, validations) {
	if(validations != null) {
		$($(validations).children()).each(function(i){
			var tipo = this.tagName;
			var format = $('format', this).text();
			var value = $('value', this).text();
			var message = $('message', this).text();
			if(tipo == 'required') {
				component.allowBlank = false;
				component.blankText  = message;
			} else if (tipo == 'maxlength') {
				component.maxLength = value;
				component.maxLengthText = message;
			} else if (tipo == 'minlength') {
				component.minLength = value;
				component.minLengthText = message;
			} else if (tipo == 'format') {
				component.format = value;
				component.invalidText = message;
			}
		});
	}
}


